package cn.xgj.sfzy.controller;

import cn.xgj.sfzy.entity.RootUser;
import cn.xgj.sfzy.service.RootUserService;
import cn.xgj.sfzy.util.Result;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @ClassName RootUserController
 * @Description TODO
 * @Author xgj
 * @Date 2024年10月22日 下午4:23
 * @Version 1.0
 */
@RestController
@RequestMapping("/rootUser")
public class RootUserController {
    @Autowired
    private RootUserService rootUserService;

    @PostMapping("/login")
    public Result login(@RequestBody RootUser rootUser) {
        RootUser user = rootUserService.login(rootUser.getRootName(), rootUser.getRootPassword());
        // 查不到
        if (user == null) {
            return Result.error("用户名或密码有误！");
        }
        //  成功
        return Result.success(user);
    }

    @RequestMapping("/findAll")
    public Result findAll(RootUser rootUser) {
        List<RootUser> list = rootUserService.findAll(rootUser);
        return Result.success(list);
    }

    //    分页查询
    @RequestMapping("/findByPage")
    public Result findByPage(
            @RequestParam(required = false, defaultValue = "1") Integer pageNum,
            @RequestParam(required = false, defaultValue = "2") Integer pageSize,
            RootUser rootUser) {
        PageInfo<RootUser> byPage = rootUserService.findByPage(pageNum, pageSize, rootUser);
        return Result.success(byPage);
    }

    // 添加
    @PostMapping
    public Result add(@RequestBody RootUser rootUser) {
        int num = rootUserService.add(rootUser);
        if (num != 0) {
            return Result.success("添加成功");
        } else {
            return Result.error("添加失败");
        }
    }

    //修改
    @PutMapping
    public Result update(@RequestBody RootUser rootUser) {
        int num = rootUserService.edit(rootUser);
        if (num != 0) {
            return Result.success("修改成功");
        } else {
            return Result.error("修改失败");
        }
    }

    //    删除
    @DeleteMapping("/{id}")
    public Result delete(@PathVariable(value = "id") Integer id) {
        int num = rootUserService.remove(id);
        if (num != 0) {
            return Result.success("删除成功");
        } else {
            return Result.error("删除失败");
        }
    }

    @GetMapping("/{id}")
    public Result findById(@PathVariable(value = "id") Integer id) {
        RootUser rootUser = rootUserService.findById(id);
        if (rootUser != null) {
            return Result.success(rootUser);
        }else {
            return Result.error("出错了");
        }
    }
}
